package com.pt25.base.dep.nacos.encrypt;

import com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.util.Properties;


/**
 * @author hzc
 * @date 2025/7/28 11:41
 */
@Configuration
public class EncryptConfig {

    @Bean("primaryEncryptor")
    StringEncryptor primaryEncryptor() throws Exception {
        // 读取整个properties文件
        Properties props = PropertiesLoaderUtils.loadProperties(
                new ClassPathResource("encrypt.properties")
        );
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(decrypt( props.getProperty("password")));
        config.setAlgorithm( props.getProperty("algorithm"));
        encryptor.setConfig(config);
        return encryptor;
    }


    @Bean
    EncryptablePropertyResolver encryptablePropertyResolver(@Qualifier("primaryEncryptor") StringEncryptor primaryEncryptor) {
        return new EncryptResolver(primaryEncryptor);
    }

    /**
     * 二次解密
     *
     * @param pwd 运维提供的加密密码
     * @return 解密后的密码
     */
    private String decrypt(String pwd) {
        //截取字符串，去掉前6位和后2为，默认规则
        return pwd.substring(3, pwd.length() - 1);
    }

}
